#!/bin/bash

log_error() {
  echo "$*" 1>&2
}

forsund --conf=./travis.conf --demon > /tmp/forsun.log 2>&1
FORSUND_PS=$(ps aux | grep forsund | grep -v grep)
if [ -z "$FORSUND_PS" ]
    then
        FORSUND_ERRORS=$(cat /tmp/forsun.log)
        log_error "forsund start failed for the following reasons:
$FORSUND_ERRORS
please run 'forsund' on your changes before committing."
    exit 1
fi

echo '#!/bin/bash' > /tmp/forsun_test.sh && echo 'echo success > /tmp/forsun_test.log' >> /tmp/forsun_test.sh
chmod +x /tmp/forsun_test.sh
forsun "set shell */2/1 * * * * * shell 'cmd=/tmp/forsun_test.sh'"
sleep 3
CMD_SUCCEDS=$(cat /tmp/forsun_test.log | grep "success")
if [ -z "$CMD_SUCCEDS" ]
    then
        FORSUND_ERRORS=$(cat /tmp/forsun.log)
        log_error "forsun shell test failed for the following reasons:
$FORSUND_ERRORS
please run 'forsund' on your changes before committing."
        ps -ef | grep forsun | grep -v grep | awk '{print $2}' | xargs kill -HUP > /dev/null 2>&1
    exit 1
fi

ps -ef | grep forsun | grep -v grep | awk '{print $2}' | xargs kill -HUP > /dev/null 2>&1
exit 0